Nested Statements
Matlab allows us to put one (or more) if statements inside of other if statements. This is known as nesting.
This example shows one if statement nested inside the true part of an if-else statement. And an if-else if statement inside the false part.
if ( boolean expression 1 ) if ( boolean expression 2 ) disp('This line displays if both boolean expression 1 and 2 are true.'); else disp('This line displays if boolean expression 1 is true and 2 is false.'); end else if ( boolean expression 3 ) disp('This line displays if boolean expression 1 is false and 3 is true.'); else disp('This line displays if boolean expression 1 is false and 3 is false.'); end end
There is no theoretical limit to the number of levels of nesting. However, there is a physical limit depending upon the amount of memory available to a program.
Dangling Else
A very common error called a "dangling-else" occurs if the else (false)
parts are not matched carefully when nesting if statements.
Carefully trace this code fragment to determine what is displayed
if temp
equals 15.
if ( temp > 212 ) disp('steam'); if ( temp < 32 ) disp('ice'); else disp('water'); end
Did you correctly predict this error?
??? Error: File: topicDisc01.m Line: 2 Column: 1 At least one END is missing: the statement may begin here.
The error occurs because Matlab does not care about the spacing and indentation of the statements and thus the above statements are interpreted as:
if ( temp > 212 ) disp('steam'); if ( temp < 32 ) disp('ice'); else disp('water'); end end
Now, you can clearly see that we need one more end
to
complete the outer if
statement. But, if we just add an end
at the end of the code fragment, we would have
a semantic error as a temperature of anything less than or equal to 212
will produce no output. Here's the code fragment that we really need to
correct the dangling else and produce the intended results:
if ( temp > 212 ) disp('steam'); else if ( temp < 32 ) disp('ice'); else disp('water'); end end